package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.resource.OperatorUserSystem;
import com.ruoyi.common.core.resource.OperatorUserSystemHolder;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.RedisCacheKeyHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.utils.SessionHelper;
import com.ruoyi.system.domain.ClientProductSys;
import com.ruoyi.system.domain.ClientUserProductRelationSys;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.ClientUserMapper;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class TokenService {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认24小时）
    @Value("${token.expireTime:24}")
    private int expireTime;


    private TimeUnit defaultTimeUnit = TimeUnit.HOURS;



    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    protected static final long MILLIS_HOURS = 60 * 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ClientUserMapper clientUserMapper;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String userKey = (String) claims.get(Constants.LOGIN_USER_ID);
            LoginUser user = redisCache.getCacheObject(userKey);
            assertOtherLoginForClientUser(token, user);
            //实时获取过期时间
            getUserProductExpireTime(user);
            return user;
        }
        return null;
    }

    private void getUserProductExpireTime(LoginUser user){
        Long userId = user.getUser().getUserId();
        Optional<String> clientType = SessionHelper.getRequestHeader(com.ruoyi.common.constant.Constants.OPERATOR_USER_SYSTEM_HEADER);
        if(!clientType.isPresent()){
            throw new CustomException("异常请求");
        }
        OperatorUserSystem userSystem = OperatorUserSystem.valueOf(clientType.get());
        switch (userSystem){
            case CLIENT_USER:
            case SYS_USER:
            case PLUGIN:
                return;
            case MERCHANTWORDS_WEB_USER:
                user.setExpireTime(getRelationInfo(userId).getExpireTime().getTime());
                break;
            default:
                log.error("异常的客户端类型:[{}]",clientType.get());

        }
    }

    private ClientUserProductRelationSys getRelationInfo(Long userId){
        return clientUserMapper.findWebAuthorityByUserId(userId,merchantWebProductId());
    }

    private Long merchantWebProductId(){
        //获取魔词web 产品id
        ClientProductSys clientProduct = clientUserMapper.findClientProductByName("merchantwords_web");
        if(StringUtils.isNull(clientProduct)){
            log.error("[WEB]登录 => 不存在魔词客户端信息,请初始化");
            throw new BaseException("服务器内部错误");
        }
        return clientProduct.getId();
    }


    private void assertOtherLoginForClientUser(String requestToken, LoginUser loginUser) {

        OperatorUserSystem operatorUserSystem = OperatorUserSystemHolder.get();
        if ((OperatorUserSystem.CLIENT_USER == operatorUserSystem || OperatorUserSystem.PLUGIN == operatorUserSystem) && loginUser != null) {
            String userTokenUniqueKey = RedisCacheKeyHelper.getUserTokenUniqueKey(operatorUserSystem, loginUser.getUser().getUserId());
            String cacheToken = redisCache.getCacheObject(userTokenUniqueKey);

            if (!requestToken.equals(cacheToken)) {
                String message = String.format("其他用户已登录账号[%s]", loginUser.getUsername());
                throw new CustomException(message);
            }
        }

    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getUuid())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(OperatorUserSystem operatorUserSystem, LoginUser loginUser) {
        if (loginUser != null) {
            //  用户id
            String userKey = RedisCacheKeyHelper.getUserUniqueKey(operatorUserSystem, loginUser.getUuid());
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String deviceId = IdUtils.fastUUID();

        String userKey = RedisCacheKeyHelper.getUserUniqueKey(OperatorUserSystemHolder.get(), deviceId);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_UUID_KEY, deviceId);
        claims.put(Constants.LOGIN_USER_ID, userKey);

        String token = createToken(claims);
        loginUser.setUuid(deviceId);
        setUserAgent(loginUser);
        cacheLoginUserAndToken(loginUser, token);

        return token;
    }

    private void cacheLoginUserAndToken(LoginUser loginUser, String token) {


        loginUser.setLoginTime(System.currentTimeMillis());

        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_HOURS);
        String userKey = RedisCacheKeyHelper.getUserUniqueKey(OperatorUserSystemHolder.get(), loginUser.getUuid());
        redisCache.setCacheObject(userKey, loginUser, expireTime, defaultTimeUnit);

        // TOKEN 缓存
        String userTokenUniqueKey = RedisCacheKeyHelper.getUserTokenUniqueKey(OperatorUserSystemHolder.get(), loginUser.getUser().getUserId());

        redisCache.setCacheObject(userTokenUniqueKey, token, expireTime, defaultTimeUnit);

    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {

        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_HOURS);
        String userKey = RedisCacheKeyHelper.getUserUniqueKey(OperatorUserSystemHolder.get(), loginUser.getUuid());
        redisCache.setCacheObject(userKey, loginUser, expireTime, defaultTimeUnit);
        // TOKEN 缓存 过期时间延长
        String userTokenUniqueKey = RedisCacheKeyHelper.getUserTokenUniqueKey(OperatorUserSystemHolder.get(), loginUser.getUser().getUserId());
        redisCache.expire(userTokenUniqueKey, expireTime, defaultTimeUnit);
//        }
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public void checkExpireTime(LoginUser loginUser) {
        Long currentTime = System.currentTimeMillis();
        Long expireTime = loginUser.getExpireTime();
        if(expireTime == null) return;

        if(expireTime < currentTime){
            throw new CustomException("已过期,请续费");
        }
    }
}
